<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 用户收件地址地区编码格式化
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300000_000015_t_user_address_update_code extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_address}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)->andWhere(['area_code' => 0]);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->update($this->tableName, ['area_code' => 0]);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }

        $provinces = (new Query())->from('{{%base_district}}')->andWhere(['level' => 1])->all();
        $list = [];
        foreach ($provinces as $province) {
            $c = substr($province['code'], 0, 2);
            $list[$c] = $province['name'];
        }

        $connect = $migration->db->createCommand();
        foreach ($rows as $row) {
            $tempcode = array_search($row['province'], $list);
            if (!$tempcode) {
                continue;
            }
            $q = (new Query())->from('{{%base_district}}')->andWhere([
                'and',
                ['level' => 3],
                ['like', 'code', $tempcode . '%', false]
            ])->andWhere([
                'or',
                ['name' => $row['district']],
                ['like', 'name', $row['district']],
            ])->select('code');

            $code = $q->scalar();
            Yii::error([
                'row' => $row,
                'tempcode' => $tempcode,
                'code' => $code,
                'sql' => $q->createCommand()->getRawSql(),
            ]);
            if (!$code) {
                continue;
            }
            $connect->update($migration->tableName, ['area_code' => $code], [
                'id' => $row['id']
            ])->execute();
        }
    }

}
